import { EventEmitter } from "eventemitter3";
import gsap from "gsap/all";
import * as PIXI from "pixi.js";
import { GameConfig } from "../type";
import { getRandomNumber } from "../util";

/**
 * 下坠元素
 *
 * @export
 * @class DropElement
 */
export class DropElement extends EventEmitter {
  url = "";

  width = 0;

  //   素材高度
  height = 0;

  //   素材放缩
  scale = 0.5;

  //  元素实例
  element = null;

  //   初始随机位置列
  initPositions = [];

  // 初始随机角度列
  initAngles = [0];

  dropDuration = 2; // 物体下落速率

  //   水平动画时长
  horizontalDuration = 1.2;

  //  水平位移边界
  horizotnalBounds = [-25, 25];

  initX = 0;

  constructor(app, gameConfig) {
    super();
  }

  //   下落动画开启
  drop() {
    this.animateX();
    this.animateY();
  }

  //   y方向动画
  animateY() {
    gsap.to(this.element, {
      y: window.innerHeight / 2,
      duration: this.dropDuration,
      ease: "none",
      onComplete: () => {
        this.app.stage?.removeChild?.(this.element);
      },
    });
  }

  //   x方向动画
  animateX() {
    if (!this.element) return;

    const [minX, maxX] = this.horizotnalBounds;
    if (!this.initX) {
      this.initX = this.element.x;
    }

    const from = {
      x: Math.max(0, this.initX + minX),
    };

    const to = {
      x: Math.min(this.initX + maxX, window.innerWidth),
    };

    const option = {
      duration: this.horizontalDuration,
      repeat: -1,
      yoyo: true,
      ease: "power1.inOut",
    };

    // 左右随机一下，from和to
    if (Math.random() > 0.5) {
      gsap.fromTo(this.element, from, {
        ...to,
        ...option,
      });
    } else {
      gsap.fromTo(this.element, to, {
        ...from,
        ...option,
      });
    }
  }

  //   创建下坠元素
  create() {
    this.element = PIXI.Sprite.from(this.url);
    this.element.width = this.width;
    this.element.height = this.height;
    this.element.anchor.set(0.5);

    // 设置随机初始坐标
    const [x, y] = this.getRandomPosition();
    this.element.x = x;
    this.element.y = window.innerHeight / 2;

    // 设置随机角度
    this.element.angle = this.getRandomAngle();
    this.element.scale.set(this.scale);

    // 监听点击事件
    this.element.interactive = true;
    this.element.on("pointerdown", (e) => {
      this.onClick(e);
    });

    this.app.stage.addChild(this.element);
  }

  //   元素click点击事件
  onClick(e) {}

  //   计算随机初始坐标f
  getRandomPosition() {
    return this.initPositions[getRandomNumber(this.initPositions.length)];
  }

  //   获取随机角度
  getRandomAngle() {
    return this.initAngles[getRandomNumber(this.initAngles.length)];
  }
}
